const { Controller } = require('egg');
const fs = require("fs")
const path = require("path")

class OrderController extends Controller {
  async getData() {
    const { ctx } = this;
    const file = JSON.parse(fs.readFileSync(path.join(__dirname, 'order.json'), { encoding: "utf-8" }))
    ctx.body = {
        code: 1,
        message: "获取成功",
        file
    }
  }

  async addDataItem() {
    const { ctx } = this;
    const { title } = ctx.request.body
    const file = JSON.parse(fs.readFileSync(path.join(__dirname, 'order.json'), { encoding: "utf-8" }))
    file.push({
        id: String(Math.random()).slice(4, 8),
        title,
        count: 1
    })
    fs.writeFileSync(path.join(__dirname, 'order.json'), JSON.stringify(file))
    ctx.body = {
        code: 1,
        message: "新增成功"
    }
  }

  async delItem() {
    const { ctx } = this;
    const { id } = ctx.request.body
    const file = JSON.parse(fs.readFileSync(path.join(__dirname, 'order.json'), { encoding: "utf-8" }))
    
    const newArr = file.filter(item => item.id !== id)

    fs.writeFileSync(path.join(__dirname, 'order.json'), JSON.stringify(newArr))
    ctx.body = {
        code: 1,
        message: "删除成功"
    }
  }

  async editItem() {
    const { ctx } = this;
    const { id, title } = ctx.request.body
    const file = JSON.parse(fs.readFileSync(path.join(__dirname, 'order.json'), { encoding: "utf-8" }))
    const newArr = file.map(item => {
        if (item.id == id) {
            return {
                ...item,
                title
            }
        } else {
            return item
        }
    })

    fs.writeFileSync(path.join(__dirname, 'order.json'), JSON.stringify(newArr))
    ctx.body = {
        code: 1,
        message: "编辑成功"
    }
  }
}

module.exports = OrderController;
